<?php
namespace app\wechat\model;
use think\Model;
define("TOKEN","nylyzg");
define('APPID',"wx7ce505b52905050b");
define('APPSECRET',"8165855991556732de5c3c0fc87a6541");
class Wechat extends Model{
	var $appid = APPID;
	var $appsecret = APPSECRET;

    //构造函数，获取Access Token
	public function __construct($appid = NULL, $appsecret = NULL)
	{
		if($appid && $appsecret){
			$this->appid = $appid;
			$this->appsecret = $appsecret;
		}

        //方法1和方法2一次只用一种，不要同时用
        //安装了memcache的环境建议用方法1，没有安装的环境建议用方法2


        // //方法1. 缓存形式
        // if (isset($_SERVER['HTTP_APPNAME'])){  //SAE环境，需要开通memcache
            // $mem = memcache_init();
        // }else {                         	   //本地环境，需已安装memcache
            // $mem = new Memcache;
            // $mem->connect('localhost', 11211) or die ("Could not connect");
        // }
        // $this->access_token = $mem->get($this->appid);
        // if (!isset($this->access_token) || empty($this->access_token)){
            // $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
            // $res = $this->http_request($url);
            // $result = json_decode($res, true);
            // $this->access_token = $result["access_token"];
            // $mem->set($this->appid, $this->access_token, 0, 3600);
        // }

        //方法2. 本地写入
		$res = file_get_contents('access_token.json');
		$result = json_decode($res, true);
		$this->expires_time = $result["expires_time"];
		$this->access_token = $result["access_token"];

		if (time() > ($this->expires_time + 3600)){
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
			$res = $this->http_request($url);
			$result = json_decode($res, true);
			$this->access_token = $result["access_token"];
			$this->expires_time = time();
			file_put_contents('access_token.json', '{"access_token": "'.$this->access_token.'", "expires_time": '.$this->expires_time.'}');
		}
	}

	public function checkSignature()
	{

        // you must define TOKEN by yourself
		if (!defined("TOKEN")) {
			throw new \think\Exception('TOKEN is not defined!');
		}
		$signature = isset($_GET["signature"]) ? $_GET["signature"] : '';
		$timestamp = isset($_GET["timestamp"]) ? $_GET["timestamp"] : '';
		$nonce = isset($_GET["nonce"]) ? $_GET["nonce"] : '';
		$token = defined('TOKEN') ? TOKEN : '';
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode($tmpArr);
		$tmpStr = sha1($tmpStr);
		if ($tmpStr == $signature) {
			return true;
		} else {
			return false;
		}
	}


    //SDK初始化
	public function sdkInit()
	{
		$postStr = isset($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : '';
		if (!empty($postStr)) {
			libxml_disable_entity_loader(true);
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			return $postObj;
		} else return false;
	}

	public function http_request($url, $data = null)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if (!empty($data)){
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}
	public function responseTextMsg($postObj, $content = '欢迎关注我们的公众号！')
    {
        $fromUsername = isset($postObj->FromUserName) ? $postObj->FromUserName : '';
        $toUsername = isset($postObj->ToUserName) ? $postObj->ToUserName : '';
        $keyword = isset($postObj->Content) ? trim($postObj->Content) : '';
        $time = time();
        $msgType = 'text';
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					<FuncFlag>0</FuncFlag>
					</xml>";
        if (!empty($keyword) && !$content) {
            //这里可自定义自动回复单文本内容
            $content = "Welcome to wechat world!";
        }
        echo sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $content);
    }
    public function debug($var)
    {
        $postObj = $this->sdkInit();
        if (is_array($var) || is_object($var) || is_bool($var)) {
            $this->responseTextMsg($postObj, var_export($var, true));
        } else
            $this->responseTextMsg($postObj, $var);
        exit;
    }

}